<template>
  <div class=''>
    <!-- 面包屑导航区域 -->
    <Bootstrap v-bind:BootstrapTitle="BootstrapTitle"></Bootstrap>
    <!-- 卡片区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button size="mini" type="warning" @click="dialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 对话框 -->
      <!-- 用户分配 -->
      <el-dialog title="权限分配" :visible.sync="setRightdialogVisible" width="35%" @close="setProwcloseWindow">
        <!-- 树 -->
        <el-tree ref="treeRef" :data="allProwList" show-checkbox node-key="id" :default-checked-keys="keyID"
          :props="treeProps" default-expand-all>
        </el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRightdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="allotRoles">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改 -->
      <el-dialog @close="modifyUserss" title="修改角色信息" :visible.sync="modifydialogVisible" width="50%">
        <el-form :model="modifyUserList" ref="modifyUserListRes" :rules="modifyRules" label-width="100px"
          class="demo-ruleForm">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="modifyUserList.name"></el-input>
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="modifyUserList.describe"></el-input>
          </el-form-item>

        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="modifydialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="modifyaddUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 添加 -->
      <el-dialog title="添加角色" :visible.sync="dialogVisible" width="50%" @close="addFomeRemove">
        <el-form :model="addForm" :rules="addRules" ref="addruleFormRef" label-width="100px">
          <el-form-item label="角色名称" prop="names">
            <el-input v-model="addForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="addForm.describe"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 对话框end -->
      <!-- 角色信息区 -->
      <el-table :data="allUserList" style="width: 100%" stripe border>
        <el-table-column type="expand" label="" width="50">
          <template slot-scope="scope">
            <el-row v-for="(item1,i1) in scope.row.children" :key="item1.id"
              :class="['bdbottom',i1 === 0? 'bdtop':'','aa']">
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeProw(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级权限 -->
              <el-col :span="19">
                <el-row :class="[i2 === 0 ? '':'bdtop','aa']" v-for="(item2,i2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeProw(scope.row,item2.id)">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag type="danger" closable v-for="(item3,i3) in item2.children" :key="item3.id"
                      @close="removeProw(scope.row,item3.id)">
                      {{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="" width="50">
        </el-table-column>
        <el-table-column prop="roleName" label="角色名称">
        </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="modifyUser(scope.row.id)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="DeleteUser(scope.row.id)">删除</el-button>
            <el-tooltip effect="dark" content="分配权限" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-help" size="mini" @click="showSetRightDialog(scope.row)">分配权限
              </el-button>
            </el-tooltip>

          </template>
        </el-table-column>
      </el-table>

    </el-card>
  </div>
</template>
<script>
import Bootstrap from "../../component/component/Bootstrap";
export default {
  components: {
    Bootstrap,
  },
  name: "",
  data() {
    return {
      BootstrapTitle: {
        first: "权限管理",
        second: "/roles",
        third: "角色列表",
      },
      modifydialogVisible: false,
      dialogVisible: false,
      setRightdialogVisible: false,
      allUserList: [],
      allProwList: [],
      // 树形控件
      treeProps: {
        label: "authName",
        children: "children",
      },
      keyID: [],
      addForm: {
        roleName: "",
        describe: "",
      },
      modifyUserList: {
        name: "",
        describe: "",
      },
      modifyRules: {
        name: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
      },
      addRules: {
        names: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
      },
    };
  },
  created() {
    this.getAllUserList();
  },
  methods: {
    async getAllUserList() {
      let res = await this.$http.get("roles");
      if (res.data.meta.status !== 200) {
        this.$message.error("获取数据失败");
      } else {
        this.$message.success("获取数据成功");
        this.allUserList = res.data.data;
        // console.log(res, "res");
      }
    },
    // 编辑
    async modifyUser(id) {
      window.sessionStorage.setItem("ids", id);
      this.modifydialogVisible = true;
      let res = await this.$http.get("roles/" + id);
      if (res.data.meta.status !== 200) {
        this.$message.error("获取角色数据失败");
      } else {
        this.$message.success("获取角色数据成功");
        this.modifyUserList.name = res.data.data.roleName;
        this.modifyUserList.describe = res.data.data.roleDesc;
      }
      // console.log(res, "res");
    },
    modifyUserss() {
      window.sessionStorage.removeItem("ids");
      this.$refs.modifyUserListRes.resetFields();
    },
    // 编辑确定
    async modifyaddUser() {
      this.modifydialogVisible = false;
      let roleName = this.modifyUserList.name;
      let roleDesc = this.modifyUserList.describe;
      let id = window.sessionStorage.getItem("ids");
      let res = await this.$http.put("roles/" + id, { roleName, roleDesc });
      if (res.data.meta.status !== 200) {
        this.$message.error("修改角色信息失败");
      } else {
        this.$message.success("修改角色信息成功");
        this.getAllUserList();
      }
    },
    // 指定权限删除
    async removeProw(id1, id2) {
      let confirm = await this.$confirm(
        "此操作将永久删除该用户信息, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      if (confirm !== "confirm") {
        this.$message.error("取消删除");
      } else {
        let ress = await this.$http.delete(`roles/${id1.id}/rights/${id2}`);
        // console.log(ress, "566651656565665");
        if (ress.data.meta.status !== 200) {
          this.$message.error(ress.data.meta.msg);
        } else {
          this.$message.success(ress.data.meta.msg);
          // this.getAllUserList();
          id1.children = ress.data.data;
        }
      }
    },
    // 删除用户资料
    DeleteUser(id) {
      this.$confirm("此操作将永久删除该用户信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let res = await this.$http.delete("roles/" + id);
          // console.log(res, "res");
          if (res.data.meta.status !== 200) {
            this.$message.error("删除角色信息失败");
          } else {
            this.getAllUserList();
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            return;
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 添加
    async addUser() {
      // let { roleName } = this.addForm;
      // let { roleDesc } = this.addForm;
      let res = await this.$http.post("roles", this.addForm);
      if (res.data.meta.status !== 201) {
        this.$message.error("添加角色失败");
      } else {
        this.$message.success("添加角色成功");
        this.dialogVisible = false;
        this.getAllUserList();
      }
    },
    // 检测关闭
    addFomeRemove() {
      this.$refs.addruleFormRef.resetFields();
    },
    setProwcloseWindow() {
      window.sessionStorage.removeItem("setrig");
      this.keyID = [];
    },
    // 权限分配-权限
    async showSetRightDialog(row) {
      window.sessionStorage.setItem("setrig", row.id);
      this.getTreeIdList(row, this.keyID);
      this.setRightdialogVisible = true;
      // 根据id显示选中的权限
      console.log(row, "row");
      let res = await this.$http.get("rights/tree");
      // console.log(res, "res");
      if (res.data.meta.status !== 200) {
        this.$message.error(res.data.meta.msg);
      } else {
        this.$message.success(res.data.meta.msg);
        this.allProwList = res.data.data;
        // console.log(this.allProwList);
      }
    },
    // 递归节点id
    getTreeIdList(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      } else {
        node.children.forEach((item) => {
          this.getTreeIdList(item, arr);
        });
      }
    },
    // 拿到所有已选中的节点然后请求修改
    async allotRoles() {
      let rowId = window.sessionStorage.getItem("setrig");

      const keys = [
        // 已选中
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      let idStr = keys.join(",");
      let res = await this.$http.post(`roles/${rowId}/rights`, { rids: idStr });
      if (res.data.meta.status !== 200) {
        this.$message.error(res.data.meta.msg);
      } else {
        this.getAllUserList();
        this.$message.success(res.data.meta.msg);
      }
      this.setRightdialogVisible = false;
    },
  },
};
</script>
<style lang='less' scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.aa {
  display: flex;
  align-items: center;
}
</style>